package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbs.dto.CommentDTO;
import com.bbs.entity.Comment;
import com.bbs.mapper.CommentMapper;
import com.bbs.service.CommentService;
import com.bbs.vo.CommentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    
    @Override
    public CommentVO createComment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        save(comment);
        return convertToVO(comment);
    }
    
    @Override
    public CommentVO getCommentById(Long id) {
        Comment comment = getById(id);
        return convertToVO(comment);
    }
    
    @Override
    public List<CommentVO> getCommentsByPostId(Long postId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getPostId, postId);
        List<Comment> comments = list(wrapper);
        return comments.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    @Override
    public CommentVO updateComment(Long id, CommentDTO commentDTO) {
        Comment comment = getById(id);
        BeanUtils.copyProperties(commentDTO, comment);
        updateById(comment);
        return convertToVO(comment);
    }
    
    @Override
    public void deleteComment(Long id) {
        removeById(id);
    }
    
    @Override
    public List<CommentVO> getCommentsByUserId(Long userId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getUserId, userId);
        List<Comment> comments = list(wrapper);
        return comments.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<CommentVO> getAllComments() {
        List<Comment> comments = this.list();
        return comments.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    private CommentVO convertToVO(Comment comment) {
        if (comment == null) {
            return null;
        }
        CommentVO vo = new CommentVO();
        BeanUtils.copyProperties(comment, vo);
        return vo;
    }
} 